package pl.ppsoft.fixlang;

import java.util.List;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceGroup;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;

public class ConfigActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {

	private static final int TEXT_TO_SPEECH_CODE = 10;
	
	public static final String PREFERENCE_MODE_PARAM = "PreferenceMode";
	
	public static final String SYNC_PREFERENCE = "sync_preference";
	public static final String URL_PREFERENCE = "url_preference";
	public static final String SPEECH_PREFERENCE = "speech_preference";
	public static final String SPEECH_ONLEARN_PREFERENCE = "speech_onlearn_preference";
	public static final String LOCALE_PREFERENCE = "locale_preference";
	public static final String PASSWORD_PREFERENCE = "password_preference";
	public static final String VOICE_PREFERENCE = "voice_preference";
	public static final String CROSS_DEFAULT_PREFERENCE = "cross_default_preference";
	public static final String QUESTIONING_METHOD_PREFERENCE = "questioning_method_preference";
	public static final String ANSWERING_METHOD_PREFERENCE = "answering_method_preference";
	public static final String LISTENING_METHOD_PREFERENCE = "listening_method_preference";
	public static final String WRITING_METHOD_PREFERENCE = "writing_method_preference";
	public static final String WRITING_SPEECH_PREFERENCE = "writing_speech_preference";	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        
        
        Bundle extras = getIntent().getExtras();
        int preferences = extras.getInt(PREFERENCE_MODE_PARAM);        
        this.addPreferencesFromResource(preferences);
        this.initSummaries(this.getPreferenceScreen());

        this.getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    private void initSummaries(PreferenceGroup pg) {
        for (int i = 0; i < pg.getPreferenceCount(); ++i) {
        	Preference p = pg.getPreference(i);
        	if (p instanceof PreferenceGroup)
        		this.initSummaries((PreferenceGroup) p); // recursion
        	else
        		this.setSummary(p);
        	}
    }
        
	@Override
	public void onSharedPreferenceChanged(SharedPreferences settings, String key) {
		Preference pref = findPreference(key);
		if ( SPEECH_PREFERENCE.equals( key ) ) {
			CheckBoxPreference check = (CheckBoxPreference)pref;
			if ( check.isChecked() ) {
		        Intent checkIntent = new Intent();
		        checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		        startActivityForResult(checkIntent, TEXT_TO_SPEECH_CODE);        

			}
		} else if ( VOICE_PREFERENCE.equals( key ) ) {
			CheckBoxPreference check = (CheckBoxPreference)pref;
			if ( check.isChecked() ) {
		        PackageManager pm = getPackageManager();
		        List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
		        if (activities.isEmpty()) {
		        	check.setChecked(false);
		        	
	        		AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
	                alertbox.setMessage( R.string.voice_not_installed );
	                alertbox.setNeutralButton(R.string.btn_ok, null );                    
	                alertbox.show();        				        	
		        }
			}
		} else {
			this.setSummary(pref);
		}
	}

	private void setSummary(Preference pref) {
		if (pref instanceof ListPreference) {
			ListPreference listPref = (ListPreference) pref;
			pref.setSummary(listPref.getEntry());
		} else if (pref instanceof EditTextPreference) {
			EditTextPreference editPref = (EditTextPreference) pref;
			if ( PASSWORD_PREFERENCE.equals( pref.getKey() ) ) {
				String text = editPref.getText();
				String value = "";
				if ( text != null ) {					
					for ( int i = 0; i < text.length(); i++ ) {
						value += "*";
					}
				}
				pref.setSummary(value);
			} else {
				pref.setSummary(editPref.getText());
			}
		}
	}	
	
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	if (requestCode == TEXT_TO_SPEECH_CODE) {
            if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {            	
            	Toast.makeText(this, R.string.speech_installed, Toast.LENGTH_SHORT).show();            	
            } else {
            	Toast.makeText(this, R.string.speech_not_installed, Toast.LENGTH_SHORT).show();
            	
                // missing data, install it
                Intent installIntent = new Intent();
                installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                startActivity(installIntent);
            }
        }
    	super.onActivityResult(requestCode, resultCode, intent);    
    }	
}
